package com.exthirteen.textgamescript.service;

import com.alibaba.fastjson.JSONObject;
import com.exthirteen.textgamescript.config.CommonConfig;
import com.exthirteen.textgamescript.config.JacksonUtil;
import com.exthirteen.textgamescript.entity.LicenseKey;
import com.exthirteen.textgamescript.model.dto.WechatMessageNotifyDTO;
import com.exthirteen.textgamescript.websocket.WebSocketClientListener;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.web.client.RestTemplate;

import java.util.concurrent.Executor;

/**
 * <p>
 * socket回调处理器
 * </p>
 *
 * @author exthirteen
 * @since 2025/5/5
 */
@Slf4j
public class WsClientListener implements WebSocketClientListener {

    private ApplicationContext applicationContext;

    private LicenseKey licenseKey;

    public WsClientListener(ApplicationContext applicationContext, LicenseKey licenseKey) {
        this.applicationContext = applicationContext;
        this.licenseKey = licenseKey;
    }

    @Override
    public void onMessage(String message) {
        RunService.setActivityTime(licenseKey.getLicense());
        Executor syncWechatNotifyExecutorPool = applicationContext.getBean("syncWechatNotifyExecutorPool",Executor.class);
        syncWechatNotifyExecutorPool.execute(() -> {
            //接收到微信消息
            JSONObject jsonObject = JSONObject.parseObject(message);
            //构建消息推送对象
            WechatMessageNotifyDTO notify = new WechatMessageNotifyDTO();
            notify.setAppId(licenseKey.getLicense());
            notify.setWxId(licenseKey.getWxId());
            WechatMessageNotifyDTO.MessageData messageData = new WechatMessageNotifyDTO.MessageData();
            messageData.setMsgType(jsonObject.getInteger("msg_type"));
            messageData.setMsgId(jsonObject.getLong("msg_id"));
            messageData.setStatus(jsonObject.getInteger("status"));
            messageData.setImgStatus(jsonObject.getInteger("img_status"));
            messageData.setCreateTime(jsonObject.getLong("create_time"));
            messageData.setMsgSource(jsonObject.getString("msg_source"));
            messageData.setNewMsgId(jsonObject.getLong("new_msg_id"));
            WechatMessageNotifyDTO.FromUserName fromUserName = new WechatMessageNotifyDTO.FromUserName();
            JSONObject jsonObjectFromUserName = jsonObject.getJSONObject("from_user_name");
            if (jsonObjectFromUserName != null){
                fromUserName.setStringValue(jsonObjectFromUserName.getString("str"));
            }
            messageData.setFromUserName(fromUserName);
            WechatMessageNotifyDTO.ToUserName toUserName = new WechatMessageNotifyDTO.ToUserName();
            JSONObject jsonObjectToUserName = jsonObject.getJSONObject("to_user_name");
            if (jsonObjectToUserName!= null){
                toUserName.setStringValue(jsonObjectToUserName.getString("str"));
            }
            messageData.setToUserName(toUserName);
            WechatMessageNotifyDTO.Content content = new WechatMessageNotifyDTO.Content();
            JSONObject jsonObjectContent = jsonObject.getJSONObject("content");
            if (jsonObjectContent!= null){
                content.setStringValue(jsonObjectContent.getString("str"));
            }
            messageData.setContent(content);
            WechatMessageNotifyDTO.ImgBuf imgBuf = new WechatMessageNotifyDTO.ImgBuf();
            JSONObject jsonObjectImgBuf = jsonObject.getJSONObject("img_buf");
            if (jsonObjectImgBuf!= null){
                imgBuf.setILenValue(jsonObjectImgBuf.getIntValue("len"));
            }
            messageData.setImgBuf(imgBuf);
            notify.setMessageData(messageData);
            //向地址推送消息
            log.info("向地址推送消息: {}", CommonConfig.CALLBACK_URL);
            log.info("推送消息内容: {}", JacksonUtil.toJsonString(notify));
            if (StringUtils.isNotEmpty(CommonConfig.CALLBACK_URL)) {
                try {
                    RestTemplate restTemplate = applicationContext.getBean(RestTemplate.class);
                    restTemplate.postForObject(CommonConfig.CALLBACK_URL, notify, String.class);
                } catch (Exception e) {
                    log.error("消息推送失败", e);
                }
            }
        });
    }

    @Override
    public void onClose(int code, String reason, boolean remote) {
        RunService.removeClient(licenseKey.getLicense());
    }

    @Override
    public void onError(Exception ex) {
        RunService.removeClient(licenseKey.getLicense());
    }
}
